package com.example.forumbackend.shiro;


import cn.hutool.core.bean.BeanUtil;
import com.example.forumbackend.entity.character.User;
import com.example.forumbackend.entity.character.UserRole;
import com.example.forumbackend.service.UserRoleService;
import com.example.forumbackend.service.UserService;
import com.example.forumbackend.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.build.Plugin;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;

/**
 * @author chenguo
 */
@Slf4j
@Component
public class UserRealm extends AuthorizingRealm {
    @Resource
    UserService userService;

    @Resource
    UserRoleService userRoleService;

    @Resource
    JwtUtils jwtUtils;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("=======进行了授权操作=======");
        User user = (User) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        List<UserRole> roleByIds = userRoleService.findRoleByIds(user.getId());
        Set<String> roleSet = new HashSet<>();
        for (UserRole roleById : roleByIds) {
            roleSet.add(roleById.getName());
        }
        authorizationInfo.setRoles(roleSet);
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("=======进行了认证操作=======");
        JwtToken jwt = (JwtToken) token;
        log.info("jwt---------->{}", jwt);
        String userId = jwtUtils.getClaimByToken((String) jwt.getPrincipal()).getSubject();
        User user = userService.getById(userId);
        if(user==null){
            throw new UnknownAccountException("账户不存在！！");
        }
        if(user.getStatus()==-1){
            throw new LockedAccountException("账户已被锁定！！");
        }
        AccountProfile profile = new AccountProfile();
        BeanUtil.copyProperties(user, profile);
        log.info("profile----------{}", profile.toString());
        return new SimpleAuthenticationInfo(profile, jwt.getCredentials(), getName());
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return super.supports(token);
    }
}
